package com.news.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.news.entity.Category;
import com.news.entity.News;
import com.news.util.PageModel;

public class CategoryDaoImpl implements CategoryDao {

	private SessionFactory session;

	@Override
	public void setSession(SessionFactory session) {
		this.session = session;
	}

	@Override
	public List<News> getAllCategory() {
		String hql = "from Category";
		Query query = session.getCurrentSession().createQuery(hql);
		return query.list();
	}

	@Override
	public Category getCategory(int cid) {
		String hql = "from Category c where c.cid=?";
		Query query = session.getCurrentSession().createQuery(hql);
		query.setInteger(0, cid);

		return (Category) query.uniqueResult();
	}

	@Override
	public PageModel getPageModelBycid(int cid, Integer currentPage,
			Integer rows) {
		Long totalsl = getAllCountBycid(cid);
		int totals = Integer.parseInt(totalsl.toString());
		List<News> datas = getAllCategoryBycid(currentPage, rows, cid);
		return new PageModel(totals, datas, rows, currentPage);
	}

	@Override
	public Long getAllCountBycid(int cid) {
		return (Long) session.getCurrentSession()
				.createQuery("select count(*) from News where c_id=?")
				.setParameter(0, cid).uniqueResult();
	}

	@Override
	public List<News> getAllCategoryBycid(int currPage, int pageSize, int cid) {
		StringBuffer sb = new StringBuffer();
		sb.append("from News as lo where c_id=?");
		Query query = session.getCurrentSession().createQuery(sb.toString());
		query.setFirstResult((currPage - 1) * pageSize);
		query.setMaxResults(pageSize);
		query.setInteger(0, cid);
		return query.list();
	}

	@Override
	public PageModel getPageModelByCid(Integer currentPage, Integer rows,
			int cid) {
		Long totalsl = getAllCount();
		int totals = Integer.parseInt(totalsl.toString());
		List<News> datas = getAllNewsByCid(currentPage, rows, cid);
		return new PageModel(totals, datas, rows, currentPage);
	}

	@Override
	public Long getAllCount() {
		return (Long) session.getCurrentSession()
				.createQuery("select count(*) from News").uniqueResult();
	}

	@Override
	public List<News> getAllNewsByCid(int currPage, int pageSize, int cid) {
		StringBuffer sb = new StringBuffer();
		sb.append("from News as lo where c_id=?");
		Query query = session.getCurrentSession().createQuery(sb.toString());
		query.setFirstResult((currPage - 1) * pageSize);
		query.setMaxResults(pageSize);
		query.setInteger(0, cid);
		return query.list();
	}
}
